from pymongo import MongoClient
import gridfs
import io
class TestFile:
    def __init__(self):
        self.client = MongoClient('127.0.0.1',27017)
        self.fsdb = self.client['testfile']
        self.fs = gridfs.GridFS(self.fsdb)
        print(self.fs)
    def insertFile(self,file_path,file_name):
        try:
            if self.fs.exists(filename=file_name):
                raise FileExistsError("文件已经存在！！")
            with open(file_path,'rb') as fileObj:
                data = fileObj.read()
                file_id = self.fs.put(data,filename=file_name)
                print(file_id)
                fileObj.close()
        except Exception as err:
            print(f"插入失败，请检查错误:{err}")
    def getFile(self,file_name):
        try:
            # 查询条件是一个对象
            file = self.fs.find_one({'filename':file_name})
            if file == None:
                raise FileNotFoundError("未找到该文件")
            file_id = file._id
            print('文件列表：%s'%(self.fs.list()))
            print('%s文件的id:%s'%(file.name,file_id))
            return file_id
        except Exception as e:
            print(f"插入失败，请检查错误:{e}")
    def downloadFile(self,file_id,downloadPath):
        try:
            file = self.fs.get(file_id)
            file_data = file.read()
            output = io.open(downloadPath,mode='wb')
            output.write(file_data)
            output.close()
            print("下载成功")
        except Exception as e:
            print(f"下载失败，请检查错误:{e}")
if __name__=='__main__':
    print("--代码运行--")
    gf=TestFile()
    print("----上传文件-----")
    file_name = '2.txt'
    file_path = '/Users/huxiaoting/Documents/2.txt' # 根据自己的文件路径调整
    gf.insertFile(file_path,file_name)
    print("-----获取文件列表-------")
    fid =  gf.getFile(file_name)
    print("-----下载文件-------")
    gf.downloadFile(fid,'/Users/huxiaoting/Documents/4.txt')